package site.cyningxu.utils;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.KeyEvent;

/**
 * Created by xuxingcan on 17-8-15.
 */
public class KeyUtil {
    private static KeyUtil instance;
    private Robot r;

    public static KeyUtil getInstance() {
        if (instance == null) {
            synchronized (KeyUtil.class) {
                if (instance == null) {
                    instance = new KeyUtil();
                }
            }
        }
        return instance;
    }

    private KeyUtil() {
        try {
            r = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }

    // shift+ 按键
    public void keyPressWithShift(int key) {
        r.keyPress(KeyEvent.VK_SHIFT);
        r.keyPress(key);
        r.keyRelease(key);
        r.keyRelease(KeyEvent.VK_SHIFT);
        r.delay(100);
    }

    // ctrl+ 按键
    public void keyPressWithCtrl(int key) {
        r.keyPress(KeyEvent.VK_CONTROL);
        r.keyPress(key);
        r.keyRelease(key);
        r.keyRelease(KeyEvent.VK_CONTROL);
        r.delay(100);
    }

    // alt+ 按键
    public void keyPressWithAlt(int key) {
        r.keyPress(KeyEvent.VK_ALT);
        r.keyPress(key);
        r.keyRelease(key);
        r.keyRelease(KeyEvent.VK_ALT);
        r.delay(100);
    }

    //打印出字符串
    public void keyPressString(Robot r, String str) {
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();//获取剪切板
        Transferable tText = new StringSelection(str);
        clip.setContents(tText, null); //设置剪切板内容
        keyPressWithCtrl(KeyEvent.VK_V);//粘贴
        r.delay(100);
    }

    //单个 按键
    public void keyPress(int key) {
        r.keyPress(key);
        r.keyRelease(key);
        r.delay(100);
    }
}
